<template>
	<div class="card-collection-wrapper">
		<CardCollectionSelect
			:cardCollectionOptions="cardCollectionOptions"
			:value="value"
			:disabled="showDetail"
			@changeValue="changeCardType"
			:prop="prop"
			:isOpenOCR="openOCR"
			@setOpenOCR="setOpenOCR"
		/>
		<div v-if="openOCR">
			<template v-if="value === 'bank-card'">
				<BindBankCard
					:identifyResult="identifyResult"
					:variableList="variableList"
					:roleList="roleList"
					:activeRoleId="activeRoleId"
					:disabled="showDetail"
					@checkRole="checkRole"
					@onCheck="onCheck"
					@changeCardProps="changeCardProps"
					@clearValue="clearValue"
				/>
			</template>
			<template v-else-if="value === 'ID-card'">
				<BindIDCardFront
					:identifyResult="identifyResult"
					:variableList="variableList"
					:roleList="roleList"
					:disabled="showDetail"
					:activeRoleId="activeRoleId"
					@checkRole="checkRole"
					@onCheck="onCheck"
					@changeCardProps="changeCardProps"
					@clearValue="clearValue"
				/>
				<BindIDCardBack
					:identifyResult="identifyResult"
					:variableList="variableList"
					:disabled="showDetail"
					:roleList="roleList"
					:activeRoleId="activeRoleId"
					@checkRole="checkRole"
					@onCheck="onCheck"
					@changeCardProps="changeCardProps"
					@clearValue="clearValue"
				/>
			</template>
		</div>
	</div>
</template>

<script>
import BindBankCard from './BindBankCard.vue';
import BindIDCardBack from './BindIDCardBack.vue';
import BindIDCardFront from './BindIDCardFront.vue';
import CardCollectionSelect from './CardCollectionSelect.vue';

import { getAllRole, getVariablesAll } from '@/api/api.js';

export default {
	components: {
		CardCollectionSelect,
		BindBankCard,
		BindIDCardFront,
		BindIDCardBack
	},
	props: {
		cardCollectionOptions: {
			type: Array,
			default: () => []
		},
		identifyResult: {
			type: Array,
			default: () => []
		},
		prop: {
			type: String,
			default: () => ''
		},
		value: {
			type: String,
			default: () => ''
		},
		openOCR: {
			type: Boolean,
			default: () => false
		},
		showDetail: {
			type: Boolean,
			default: () => false
		}
	},
	data() {
		return {
			// collectionType: '', // 卡证收集类型，身份证、银行卡
			variableList: [], // 变量列表
			selectedValues: [], // 已选择的变量名
			checkStatus: {}, // 每个角色对应的全选状态
			roleList: [], // 角色列表
			activeRoleId: 0, // 当前选择的角色id
			scenId: JSON.parse(sessionStorage.getItem('sceneData'))?.id || this.$route.params.scenId,
			pageData: {
				page: 1,
				pageSize: 100000,
				total: 0
			},
			identifyResult: []
		};
	},
	async mounted() {
		console.log(this.showDetail);
		// this.collectionType = this.value || '';
		await this.initAllRole();
	},
	methods: {
		async changeCardType(type) {
			// this.collectionType = type;
			this.$emit('input', this.prop, type);
			await this.initAllRole();
		},
		// 初始化所有角色
		initAllRole() {
			getAllRole(this.scenId)
				.then(res => {
					// id: 302, name: '访客'
					this.roleList = res.data.data;
					this.activeRoleId = res.data.data[0].id;
					this.roleList.map(item => {
						this.checkStatus[item.id] = false;
					});
					this.getVariablesAll();
				})
				.catch(err => {
					console.log(err);
				});
		},
		getVariablesAll() {
			this.variableList = [];
			let param = {
				scenId: this.scenId,
				page: 1,
				pageSize: 10000
			};
			getVariablesAll(param)
				.then(res => {
					if (res.data.data && res.data.data.rows) {
						let list = [];
						res.data.data.rows.map(item => {
							if (item.roleId) {
								const data = {
									id: item.id,
									name: item.name,
									roleId: item.roleId,
									dataMasking: item.dataMasking,
									params: item.params,
									url: item.url,
									method: item.method,
									linkedKey: item.linkedKey,
									isDefault: item.isDefault,
									key: item.name,
									property: item.type,
									content: '',
									initMode: item.initMode,
									scenId: this.scenId,
									roleName: item.bizscenario_role.name
								};
								list.push(data);
							}
						});
						this.variableList = list;
						this.pageData.total = res.data.data.count;
					} else {
						console.warn('get variable list error ', res.data);
					}
				})
				.catch(err => {
					console.log(err);
					this.$message.error('获取客户信息变量列表失败！');
				});
		},

		checkRole(id) {
			this.activeRoleId = id;
			console.log('this.activeRoleId:', this.activeRoleId);
		},

		onRemoveTag(value) {
			for (const item of this.variableList) {
				const text = `客户信息-${item.roleName}-${item.name}`;
				if (value === text) {
					this.removeSelectVariable(item.id);
					break;
				}
			}
			this.checkFullSelectStatus();

			this.onChange();
		},

		onChange() {
			let list = [];
			this.selectedValues.map(id => {
				this.variableList.map(item => {
					if (id === item.id) {
						list.push(item);
					}
				});
			});
			this.$emit('input', this.prop, list);
		},

		setOpenOCR(status) {
			this.$emit('input', 'openOCR', status);
		},

		onCheck(status, data) {
			// if (checked) {
			// 	this.addSelectVariable(item.id);
			// } else {
			// 	this.removeSelectVariable(item.id);
			// }
			// this.onChange();
			console.log(status, data);
		},

		clearValue(data) {
			const { id = null, type = null } = data;
			this.identifyResult = this.identifyResult.filter(item => item.fieldName !== type);
			this.$emit('input', 'identifyResult', this.identifyResult);
		},

		changeCardProps(type, data) {
			let field = {
				id: null,
				name: '',
				fieldName: '', //身份证号
				parameterName: '' // 参数名 绑定的变量
			};
			const keyEnum = {
				cardType: '卡片类型',
				cardNumber: '卡号',
				idNumber: '身份证号',
				name: '姓名',
				sex: '性别',
				ethnicity: '民族',
				birthDate: '出生日期',
				address: '住址',
				issueAuthority: '签发机关',
				validPeriod: '有效日期',
				bankName: '银行',
				validToDate: '有效期'
			};
			if (keyEnum[type]) {
				field.name = keyEnum[type];
			}
			field.fieldName = type;
			field.id = data.id;
			field.parameterName = `{{客户信息_${data.roleName}_${data.key}_${data.id}}}`;
			let idx = this.identifyResult.findIndex(item => item.fieldName === field.fieldName);
			if (idx === -1) {
				this.identifyResult = [...this.identifyResult, field];
			} else {
				this.identifyResult[idx] = field;
			}
			this.$emit('input', 'identifyResult', this.identifyResult);
			console.log('changeCardProps:', this.identifyResult);
		},

		addSelectVariable(vid) {
			if (!this.selectedValues.includes(vid)) {
				this.selectedValues.push(vid);
			}
		},
		removeSelectVariable(vid) {
			const index = this.selectedValues.indexOf(vid);
			if (index >= 0) {
				this.selectedValues.splice(index, 1);
			}
		},

		getSelectedTextList() {
			let list = [];
			this.selectedValues.map(id => {
				for (const item of this.variableList) {
					if (id === item.id) {
						list.push(`客户信息-${item.roleName}-${item.name}`);
						break;
					}
				}
			});

			return list;
		}
	}
};
</script>

<style></style>
